import axios from 'axios';
import { Message } from 'element-ui';
import store from '@/store/index';
import settings from '@/settings';
import qs from 'qs';
import _ from 'lodash';
import { handleError } from './utils';
// create an axios instance
const service = axios.create();

function rejectHandle(reject, error, throwError) {
  if (throwError) {
    reject(error);
  } else {
    handleError(error, true);
  }
}

service.interceptors.request.use(
  config => {
    const token = store.state.token;
    token && (config.headers.Authorization = token);
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data;

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      });

      //   // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      //   if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
      //     // to re-login
      //     MessageBox.confirm(
      //       "You have been logged out, you can cancel to stay on this page, or log in again",
      //       "Confirm logout",
      //       {
      //         confirmButtonText: "Re-Login",
      //         cancelButtonText: "Cancel",
      //         type: "warning"
      //       }
      //     ).then(() => {
      //       store.dispatch("user/resetToken").then(() => {
      //         location.reload();
      //       });
      //     });
      //   }
      return Promise.reject(new Error(res.message || 'Error'));
    }
    return res;
  },
  error => {
    console.log('err' + error); // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

async function fetch(
  serverName,
  path,
  params,
  dataType = 'form',
  method = 'POST',
  throwError = false
) {
  let url = settings.getServer(serverName) + path;
  console.log(url, '=========url');

  return new Promise((resolve, reject) => {
    let currentUser = store.getters.currentUser;
    let sessionToken = '';
    if (currentUser) {
      sessionToken = currentUser.id;
    }
    let m = method || 'POST';
    let options = {
      headers: {
        authToken: sessionToken || 'daf4e474-f101-4c5f-a0d8-ab34b86d314b'
      },
      withCredentials: true,
      url: url,
      method: m
    };
    if (m.toUpperCase() === 'GET') {
      options = _.merge(options, {
        params: params || {}
      });
    } else {
      if (typeof params === 'FormData') {
        options = _.merge(options, {
          data: params || {},
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
      } else if (dataType === 'form') {
        if (typeof params !== 'string') {
          params = qs.stringify(params || {});
        }
        options = _.merge(options, {
          data: params,
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });
      } else {
        options = _.merge(options, {
          data: params || {}
        });
      }
    }
    axios(options).then(
      response => {
        if (response.data.code === 200) {
          resolve(response.data);
        } else if (response.data.code === 401) {
          // deps.router.push({
          //   name: "PassportLogin",
          //   query: {
          //     redirect: window.location.href
          //   }
          // });
        } else {
          rejectHandle(reject, response.data, throwError);
        }
      },
      error => {
        let message = '无法连接到服务器，请检查您的网络';
        if (error.response) {
          message += '[' + error.response.status + ']';
        }
        error.code = 500;
        error.message = message;
        error.data = null;
        rejectHandle(reject, error, throwError);
      }
    );
  });
}
service.fetch = fetch;

export default service;
